﻿using ProxyServer.Acme;
using Quartz;

namespace ProxyServer.Quartz.Jobs
{
    [DisallowConcurrentExecution]
    public class CheckAccountJob : IJob
    {
        public static readonly JobKey Key = new JobKey(nameof(CheckAccountJob));
        private readonly IServiceProvider _serviceProvider;
        private readonly ILogger<CheckAccountJob> _logger;

        public CheckAccountJob(IServiceProvider serviceProvider, ILogger<CheckAccountJob> logger)
        {
            _serviceProvider = serviceProvider;
            _logger = logger;
        }

        public async Task Execute(IJobExecutionContext context)
        {
            using var scope = _serviceProvider.CreateAsyncScope();

            try
            {
                IAcmeState state = _serviceProvider.GetRequiredService<CheckForAcmeAccountState>();
                while (!context.CancellationToken.IsCancellationRequested)
                {
                    _logger.LogInformation("[CheckForAcmeAccount] state transition: moving to {state}", state.GetType().Name);
                    state = await state.MoveNextAsync(context.CancellationToken);
                }
            }
            catch (OperationCanceledException)
            {
                _logger.LogDebug("State machine cancellation requested. Exiting...");
            }
            catch (Exception ex)
            {
                _logger.LogError(0, ex, "ACME state machine encountered unhandled error");
            }
        }
    }
}
